# coding:utf-8
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.http import JsonResponse
from utils.code_config import *
from utils.common_util import resp_decorator
from utils.views import format_errors
from article.models import Article
from article.serializers import ArticleDetailSerializer,ArticleListSerializer


class ArticleList(APIView):
    @staticmethod
    def get_article():
        queryset = Article.objects.all()
        return queryset
    def get(self, request):

        serializer = ArticleListSerializer(self.get_article(), many=True)
        # 返回 Json 数据
        return Response(serializer.data)

    def post(self,request):
        serializer = ArticleListSerializer(data=request.data)
        try:
            serializer.is_valid()
            serializer.save()
            return JsonResponse(**CODE_0.update({"data":serializer.data}))
        except:
            return JsonResponse({**CODE_401,'msg':format_errors(ser=serializer)})

class ArticleDetail(APIView):
    """文章详情视图"""
    @staticmethod
    def get_object(pk):
        """获取单个文章对象"""
        try:
            article = Article.objects.get(pk=pk)
            return article
        except:
            return None


    @resp_decorator
    def get(self, request):
        ar_id = request.GET.get("id")
        if not ar_id:
            return JsonResponse({**CODE_401})
        articles = self.get_object(ar_id)
        # if not articles:
        #     CODE_401['msg']=""
        #     return JsonResponse({**CODE_401})
        serializer = ArticleDetailSerializer(articles)
        res = {**CODE_0, "data": serializer.data}
        return JsonResponse(res)

    def put(self, request, pk):
        article = Article.objects.get(pk=pk)
        serializer = ArticleDetailSerializer(article, data=request.data)
        # 验证提交的数据是否合法
        # 不合法则返回400
        if serializer.is_valid():
            # 序列化器将持有的数据反序列化后，
            # 保存到数据库中
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        article = Article.objects.get(pk=pk)
        article.delete()
        # 删除成功后返回204
        return Response(status=status.HTTP_204_NO_CONTENT)
